{% extends "base.html" %}

{% block title %}已确认预约 - 乒乓球培训管理系统{% endblock %}

{% block page_title %}已确认预约{% endblock %}

{% block extra_css %}
<style>
    .stats-cards {
        margin-bottom: 20px;
    }

    .stat-card {
        background: white;
        border-radius: 8px;
        padding: 20px;
        text-align: center;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        transition: all 0.2s ease;
    }

    .stat-card:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 8px rgba(0,0,0,0.15);
    }

    .stat-card.confirmed {
        border-left: 4px solid #28a745;
    }

    .stat-card.completed {
        border-left: 4px solid #007bff;
    }

    .stat-card.cancelled {
        border-left: 4px solid #dc3545;
    }

    .stat-number {
        font-size: 2rem;
        font-weight: bold;
        margin-bottom: 5px;
    }

    .stat-number.confirmed {
        color: #28a745;
    }

    .stat-number.completed {
        color: #007bff;
    }

    .stat-number.cancelled {
        color: #dc3545;
    }

    .stat-label {
        color: #6c757d;
        font-size: 0.9rem;
    }

    .reservation-card {
        background: white;
        border-radius: 8px;
        padding: 20px;
        margin-bottom: 15px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        transition: all 0.2s ease;
        border-left: 4px solid #28a745;
    }

    .reservation-card:hover {
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(0,0,0,0.15);
    }

    .reservation-card.completed {
        border-left-color: #007bff;
        background: linear-gradient(135deg, #f8f9ff 0%, #ffffff 100%);
    }

    .reservation-card.cancelled {
        border-left-color: #dc3545;
        background: linear-gradient(135deg, #fff5f5 0%, #ffffff 100%);
    }

    .reservation-card.upcoming {
        border-left-color: #ffc107;
        background: linear-gradient(135deg, #fffbf0 0%, #ffffff 100%);
    }

    .student-header {
        display: flex;
        align-items: center;
        margin-bottom: 15px;
    }

    .student-avatar {
        width: 50px;
        height: 50px;
        border-radius: 50%;
        background: #007bff;
        color: white;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 15px;
        font-weight: bold;
        font-size: 1.2rem;
    }

    .student-info h6 {
        margin: 0 0 5px 0;
        font-weight: 600;
    }

    .student-contact {
        color: #6c757d;
        font-size: 0.9rem;
    }

    .status-badge {
        padding: 6px 12px;
        border-radius: 15px;
        font-size: 0.8rem;
        font-weight: 500;
        text-transform: uppercase;
        letter-spacing: 0.5px;
    }

    .status-confirmed {
        background: #d4edda;
        color: #155724;
        border: 1px solid #c3e6cb;
    }

    .status-completed {
        background: #d1ecf1;
        color: #0c5460;
        border: 1px solid #bee5eb;
    }

    .status-cancelled {
        background: #f8d7da;
        color: #721c24;
        border: 1px solid #f5c6cb;
    }

    .status-no_show {
        background: #e2e3e5;
        color: #383d41;
        border: 1px solid #d6d8db;
    }

    .time-block {
        background: #f8f9fa;
        border-radius: 6px;
        padding: 12px;
        margin-bottom: 10px;
    }

    .time-main {
        font-size: 1.1rem;
        font-weight: 600;
        color: #495057;
        margin-bottom: 5px;
    }

    .time-date {
        color: #6c757d;
        font-size: 0.9rem;
    }

    .time-remaining {
        font-size: 0.8rem;
        color: #28a745;
        margin-top: 5px;
    }

    .course-details {
        background: #e3f2fd;
        border-radius: 6px;
        padding: 10px;
        margin-bottom: 10px;
    }

    .course-details .detail-item {
        display: flex;
        justify-content: space-between;
        margin-bottom: 5px;
    }

    .course-details .detail-item:last-child {
        margin-bottom: 0;
    }

    .action-buttons {
        display: flex;
        gap: 8px;
        flex-wrap: wrap;
    }

    .btn-action {
        padding: 6px 12px;
        font-size: 0.85rem;
        border-radius: 6px;
    }

    .upcoming-indicator {
        position: absolute;
        top: 15px;
        right: 15px;
        background: linear-gradient(135deg, #ff6b6b 0%, #ee5a52 100%);
        color: white;
        padding: 4px 8px;
        border-radius: 12px;
        font-size: 0.75rem;
        font-weight: 500;
        animation: pulse 2s infinite;
    }

    @keyframes pulse {
        0% { opacity: 1; }
        50% { opacity: 0.7; }
        100% { opacity: 1; }
    }

    .filter-tabs {
        background: white;
        border-radius: 8px;
        padding: 20px;
        margin-bottom: 20px;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }

    .status-tab {
        padding: 8px 16px;
        border: 1px solid #dee2e6;
        background: white;
        color: #6c757d;
        text-decoration: none;
        border-radius: 20px;
        margin-right: 10px;
        margin-bottom: 10px;
        display: inline-block;
        transition: all 0.2s ease;
    }

    .status-tab.active {
        background: #007bff;
        color: white;
        border-color: #007bff;
    }

    .status-tab:hover {
        background: #f8f9ff;
        border-color: #007bff;
        color: #007bff;
        text-decoration: none;
    }

    .status-tab.active:hover {
        background: #0056b3;
        color: white;
    }

    .filter-section {
        background: white;
        border-radius: 8px;
        padding: 20px;
        margin-bottom: 20px;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }

    .empty-state {
        text-align: center;
        padding: 60px 20px;
        color: #6c757d;
    }

    .empty-state i {
        font-size: 4rem;
        margin-bottom: 20px;
        color: #dee2e6;
    }

    .cancel-reason {
        background: #fff3cd;
        border: 1px solid #ffeaa7;
        border-radius: 6px;
        padding: 8px;
        margin-top: 10px;
        font-size: 0.85rem;
        color: #856404;
    }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <!-- 统计卡片 -->
    <div class="stats-cards">
        <div class="row">
            <div class="col-md-4">
                <div class="stat-card confirmed">
                    <div class="stat-number confirmed">{{ statistics.confirmed_count }}</div>
                    <div class="stat-label">已确认预约</div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="stat-card completed">
                    <div class="stat-number completed">{{ statistics.completed_count }}</div>
                    <div class="stat-label">已完成课程</div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="stat-card cancelled">
                    <div class="stat-number cancelled">{{ statistics.cancelled_count }}</div>
                    <div class="stat-label">已取消预约</div>
                </div>
            </div>
        </div>
    </div>

    <!-- 状态筛选标签 -->
    <div class="filter-tabs">
        <div class="row align-items-center">
            <div class="col-md-8">
                <div class="d-flex flex-wrap">
                    <a href="{{ url_for('coach_reservations.confirmed', status='confirmed') }}"
                       class="status-tab {% if current_status == 'confirmed' %}active{% endif %}">
                        <i class="bi bi-calendar-check"></i> 已确认
                    </a>
                    <a href="{{ url_for('coach_reservations.confirmed', status='completed') }}"
                       class="status-tab {% if current_status == 'completed' %}active{% endif %}">
                        <i class="bi bi-check-circle"></i> 已完成
                    </a>
                    <a href="{{ url_for('coach_reservations.confirmed', status='cancelled') }}"
                       class="status-tab {% if current_status == 'cancelled' %}active{% endif %}">
                        <i class="bi bi-x-circle"></i> 已取消
                    </a>
                    <a href="{{ url_for('coach_reservations.confirmed', status='all') }}"
                       class="status-tab {% if current_status == 'all' %}active{% endif %}">
                        <i class="bi bi-list"></i> 全部
                    </a>
                </div>
            </div>
            <div class="col-md-4 text-end">
                <a href="{{ url_for('coach_reservations.pending') }}" class="btn btn-warning">
                    <i class="bi bi-clock-history"></i> 待确认预约
                </a>
                <a href="{{ url_for('coach_reservations.schedule') }}" class="btn btn-primary">
                    <i class="bi bi-calendar3"></i> 课程表
                </a>
            </div>
        </div>
    </div>

    <!-- 日期筛选器 -->
    <div class="filter-section">
        <form method="GET" action="{{ url_for('coach_reservations.confirmed') }}">
            <input type="hidden" name="status" value="{{ current_status }}">
            <div class="row g-3 align-items-end">
                <div class="col-md-3">
                    <label class="form-label">开始日期</label>
                    <input type="date" name="start_date" class="form-control"
                           value="{{ filter_params.start_date }}">
                </div>
                <div class="col-md-3">
                    <label class="form-label">结束日期</label>
                    <input type="date" name="end_date" class="form-control"
                           value="{{ filter_params.end_date }}">
                </div>
                <div class="col-md-2">
                    <button type="submit" class="btn btn-primary w-100">
                        <i class="bi bi-search"></i> 筛选
                    </button>
                </div>
                <div class="col-md-2">
                    <a href="{{ url_for('coach_reservations.confirmed', status=current_status) }}"
                       class="btn btn-outline-secondary w-100">
                        <i class="bi bi-arrow-clockwise"></i> 重置
                    </a>
                </div>
                <div class="col-md-2">
                    <button type="button" class="btn btn-info w-100" onclick="exportData()">
                        <i class="bi bi-download"></i> 导出
                    </button>
                </div>
            </div>
        </form>
    </div>

    <!-- 预约列表 -->
    <div class="row">
        {% if reservations %}
            {% for reservation in reservations %}
            <div class="col-12">
                <div class="reservation-card {{ reservation.status }} {% if reservation.is_upcoming() %}upcoming{% endif %}"
                     data-reservation-id="{{ reservation.id }}">

                    <!-- 即将开始指示器 -->
                    {% if reservation.is_upcoming() %}
                    <div class="upcoming-indicator">
                        即将开始
                    </div>
                    {% endif %}

                    <div class="row">
                        <div class="col-md-3">
                            <!-- 学员信息 -->
                            <div class="student-header">
                                <div class="student-avatar">
                                    {{ reservation.student.real_name[0] }}
                                </div>
                                <div class="student-info">
                                    <h6>{{ reservation.student.real_name }}</h6>
                                    <div class="student-contact">
                                        <i class="bi bi-telephone"></i>
                                        {{ reservation.student.phone }}
                                    </div>
                                </div>
                            </div>

                            <!-- 状态标签 -->
                            <div class="status-badge status-{{ reservation.status }}">
                                {{ reservation.get_status_display() }}
                            </div>
                        </div>

                        <div class="col-md-3">
                            <!-- 时间信息 -->
                            <div class="time-block">
                                <div class="time-main">
                                    <i class="bi bi-clock"></i>
                                    {{ reservation.start_time.strftime('%H:%M') }} - {{ reservation.end_time.strftime('%H:%M') }}
                                </div>
                                <div class="time-date">
                                    {{ reservation.reservation_date.strftime('%Y年%m月%d日') }}
                                    ({{ reservation.reservation_date.strftime('%A') }})
                                </div>
                                {% if reservation.status == 'confirmed' %}
                                    {% set time_until = reservation.get_datetime_start() - current_datetime %}
                                    {% if time_until.total_seconds() > 0 %}
                                    <div class="time-remaining">
                                        {% set hours = (time_until.total_seconds() / 3600) | int %}
                                        {% if hours >= 24 %}
                                            {{ (hours / 24) | int }}天后开始
                                        {% elif hours > 0 %}
                                            {{ hours }}小时后开始
                                        {% else %}
                                            即将开始
                                        {% endif %}
                                    </div>
                                    {% endif %}
                                {% endif %}
                            </div>
                        </div>

                        <div class="col-md-3">
                            <!-- 课程详情 -->
                            <div class="course-details">
                                <div class="detail-item">
                                    <span><i class="bi bi-grid-3x3"></i> 球台</span>
                                    <span>{{ reservation.table.name }}</span>
                                </div>
                                <div class="detail-item">
                                    <span><i class="bi bi-clock"></i> 时长</span>
                                    <span>{{ reservation.duration_minutes }}分钟</span>
                                </div>
                                <div class="detail-item">
                                    <span><i class="bi bi-currency-dollar"></i> 费用</span>
                                    <span class="text-success fw-bold">¥{{ "%.2f"|format(reservation.get_price_yuan()) }}</span>
                                </div>
                                {% if reservation.created_at %}
                                <div class="detail-item">
                                    <span><i class="bi bi-calendar-plus"></i> 预约时间</span>
                                    <span>{{ reservation.created_at.strftime('%m-%d %H:%M') }}</span>
                                </div>
                                {% endif %}
                            </div>

                            <!-- 取消原因（如果有） -->
                            {% if reservation.status == 'cancelled' and reservation.cancel_reason %}
                            <div class="cancel-reason">
                                <strong>取消原因：</strong><br>
                                {{ reservation.cancel_reason }}
                            </div>
                            {% endif %}
                        </div>

                        <div class="col-md-3">
                            <!-- 操作按钮 -->
                            <div class="action-buttons">
                                <a href="{{ url_for('coach_reservations.detail', reservation_id=reservation.id) }}"
                                   class="btn btn-outline-primary btn-action">
                                    <i class="bi bi-eye"></i> 详情
                                </a>

                                {% if reservation.status == 'confirmed' %}
                                    {% if reservation.can_be_completed() %}
                                    <button type="button" class="btn btn-success btn-action"
                                            onclick="completeReservation({{ reservation.id }})">
                                        <i class="bi bi-check-circle"></i> 完成
                                    </button>
                                    {% endif %}

                                    {% if reservation.can_be_cancelled() %}
                                    <a href="{{ url_for('coach_reservations.cancel', reservation_id=reservation.id) }}"
                                       class="btn btn-warning btn-action">
                                        <i class="bi bi-x-circle"></i> 取消
                                    </a>
                                    {% endif %}

                                    {% if reservation.get_datetime_start() <= current_datetime %}
                                    <button type="button" class="btn btn-secondary btn-action"
                                            onclick="markNoShow({{ reservation.id }})">
                                        <i class="bi bi-person-x"></i> 未出席
                                    </button>
                                    {% endif %}
                                {% endif %}

                                <a href="tel:{{ reservation.student.phone }}" class="btn btn-outline-success btn-action">
                                    <i class="bi bi-telephone"></i> 联系
                                </a>

                                {% if reservation.status == 'completed' %}
                                <a href="{{ url_for('evaluations.view', reservation_id=reservation.id) }}"
                                   class="btn btn-outline-info btn-action">
                                    <i class="bi bi-star"></i> 评价
                                </a>
                                {% endif %}
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            {% endfor %}

            <!-- 分页导航 -->
            {% if pagination and pagination.pages > 1 %}
            <div class="col-12">
                <nav aria-label="分页导航" class="mt-4">
                    <ul class="pagination justify-content-center">
                        {% if pagination.has_prev %}
                        <li class="page-item">
                            <a class="page-link" href="{{ url_for('coach_reservations.confirmed', page=pagination.prev_num, **filter_params) }}">
                                上一页
                            </a>
                        </li>
                        {% endif %}

                        {% for page_num in pagination.iter_pages() %}
                            {% if page_num %}
                                {% if page_num != pagination.page %}
                                <li class="page-item">
                                    <a class="page-link" href="{{ url_for('coach_reservations.confirmed', page=page_num, **filter_params) }}">
                                        {{ page_num }}
                                    </a>
                                </li>
                                {% else %}
                                <li class="page-item active">
                                    <span class="page-link">{{ page_num }}</span>
                                </li>
                                {% endif %}
                            {% else %}
                            <li class="page-item disabled">
                                <span class="page-link">...</span>
                            </li>
                            {% endif %}
                        {% endfor %}

                        {% if pagination.has_next %}
                        <li class="page-item">
                            <a class="page-link" href="{{ url_for('coach_reservations.confirmed', page=pagination.next_num, **filter_params) }}">
                                下一页
                            </a>
                        </li>
                        {% endif %}
                    </ul>
                    <div class="text-center text-muted mt-2">
                        显示第 {{ pagination.per_page * (pagination.page - 1) + 1 }} -
                        {{ pagination.per_page * pagination.page if pagination.page < pagination.pages else pagination.total }} 条，
                        共 {{ pagination.total }} 条记录
                    </div>
                </nav>
            </div>
            {% endif %}

        {% else %}
            <div class="col-12">
                <div class="empty-state">
                    <i class="bi bi-calendar-x"></i>
                    <h5>暂无
                        {% if current_status == 'confirmed' %}已确认
                        {% elif current_status == 'completed' %}已完成
                        {% elif current_status == 'cancelled' %}已取消
                        {% else %}
                        {% endif %}
                        预约记录
                    </h5>
                    <p class="text-muted">当前筛选条件下没有找到相关预约</p>
                    {% if current_status != 'confirmed' %}
                    <a href="{{ url_for('coach_reservations.confirmed', status='confirmed') }}" class="btn btn-primary">
                        <i class="bi bi-calendar-check"></i> 查看已确认预约
                    </a>
                    {% endif %}
                </div>
            </div>
        {% endif %}
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
// 完成课程
function completeReservation(reservationId) {
    if (!confirm('确定要标记此课程为已完成吗？')) {
        return;
    }

    fetch(`/coach-reservations/api/complete/${reservationId}`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': document.querySelector('meta[name=csrf-token]').getAttribute('content')
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showToast('success', '课程已标记为完成');

            // 更新预约卡片状态
            const card = document.querySelector(`[data-reservation-id="${reservationId}"]`);
            if (card) {
                card.classList.remove('confirmed', 'upcoming');
                card.classList.add('completed');

                // 更新状态标签
                const statusBadge = card.querySelector('.status-badge');
                statusBadge.className = 'status-badge status-completed';
                statusBadge.textContent = '已完成';

                // 移除即将开始指示器
                const upcomingIndicator = card.querySelector('.upcoming-indicator');
                if (upcomingIndicator) {
                    upcomingIndicator.remove();
                }

                // 更新操作按钮
                const actionButtons = card.querySelector('.action-buttons');
                const completeBtn = actionButtons.querySelector('button[onclick*="completeReservation"]');
                const cancelBtn = actionButtons.querySelector('a[href*="cancel"]');
                const noShowBtn = actionButtons.querySelector('button[onclick*="markNoShow"]');

                if (completeBtn) completeBtn.remove();
                if (cancelBtn) cancelBtn.remove();
                if (noShowBtn) noShowBtn.remove();

                // 添加评价按钮
                const evaluationBtn = document.createElement('a');
                evaluationBtn.href = `/evaluations/view/${reservationId}`;
                evaluationBtn.className = 'btn btn-outline-info btn-action';
                evaluationBtn.innerHTML = '<i class="bi bi-star"></i> 评价';
                actionButtons.appendChild(evaluationBtn);
            }
        } else {
            showToast('error', data.message);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showToast('error', '操作失败，请重试');
    });
}

// 标记未出席
function markNoShow(reservationId) {
    if (!confirm('确定要标记此学员为未出席吗？')) {
        return;
    }

    fetch(`/coach-reservations/api/mark-no-show/${reservationId}`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': document.querySelector('meta[name=csrf-token]').getAttribute('content')
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showToast('success', '已标记为未出席');

            // 更新预约卡片状态
            const card = document.querySelector(`[data-reservation-id="${reservationId}"]`);
            if (card) {
                card.classList.remove('confirmed', 'upcoming');

                // 更新状态标签
                const statusBadge = card.querySelector('.status-badge');
                statusBadge.className = 'status-badge status-no_show';
                statusBadge.textContent = '未出席';

                // 移除操作按钮
                const actionButtons = card.querySelector('.action-buttons');
                const completeBtn = actionButtons.querySelector('button[onclick*="completeReservation"]');
                const cancelBtn = actionButtons.querySelector('a[href*="cancel"]');
                const noShowBtn = actionButtons.querySelector('button[onclick*="markNoShow"]');

                if (completeBtn) completeBtn.remove();
                if (cancelBtn) cancelBtn.remove();
                if (noShowBtn) noShowBtn.remove();
            }
        } else {
            showToast('error', data.message);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showToast('error', '操作失败，请重试');
    });
}

// 导出数据
function exportData() {
    const params = new URLSearchParams(window.location.search);
    params.set('export', 'true');
    window.open(`${window.location.pathname}?${params.toString()}`);
}

// 显示提示消息
function showToast(type, message) {
    const toast = document.createElement('div');
    toast.className = `alert alert-${type === 'success' ? 'success' : type === 'error' ? 'danger' : 'info'} alert-dismissible`;
    toast.style.position = 'fixed';
    toast.style.top = '20px';
    toast.style.right = '20px';
    toast.style.zIndex = '9999';
    toast.innerHTML = `
        ${message}
        <button type="button" class="btn-close" onclick="this.parentElement.remove()"></button>
    `;

    document.body.appendChild(toast);

    setTimeout(() => {
        if (toast.parentElement) {
            toast.remove();
        }
    }, 3000);
}

// 页面加载完成后的初始化
document.addEventListener('DOMContentLoaded', function() {
    // 设置默认日期范围
    const startDateInput = document.querySelector('input[name="start_date"]');
    const endDateInput = document.querySelector('input[name="end_date"]');

    if (startDateInput && !startDateInput.value) {
        const thirtyDaysAgo = new Date();
        thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
        startDateInput.value = thirtyDaysAgo.toISOString().split('T')[0];
    }

    if (endDateInput && !endDateInput.value) {
        const today = new Date();
        endDateInput.value = today.toISOString().split('T')[0];
    }

    // 定期刷新即将开始的预约状态
    setInterval(refreshUpcomingStatus, 60000); // 每分钟刷新一次
});

// 刷新即将开始的预约状态
function refreshUpcomingStatus() {
    const upcomingCards = document.querySelectorAll('.reservation-card.upcoming');
    if (upcomingCards.length > 0) {
        // 检查是否需要刷新页面或更新状态
        location.reload();
    }
}

// 键盘快捷键
document.addEventListener('keydown', function(e) {
    if (e.ctrlKey || e.metaKey) {
        switch (e.key) {
            case 'r':
                e.preventDefault();
                location.reload();
                break;
            case 'e':
                e.preventDefault();
                exportData();
                break;
        }
    }
});
</script>
{% endblock %}